<template>
  <div class="delivery-layout">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <el-icon class="logo-icon"><Van /></el-icon>
          <span>坤哥物流 - 配送端</span>
        </div>
      </div>
      <div class="header-center">
        <div class="quick-stats">
          <div class="stat-item">
            <el-icon><Clock /></el-icon>
            <span>{{ currentTime }}</span>
          </div>
          <div class="stat-item">
            <el-icon><Bell /></el-icon>
            <span>{{ notificationCount }} 条通知</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-popover
          placement="bottom"
          width="320"
          trigger="click"
          v-model:visible="notificationPopoverVisible"
        >
          <template #reference>
            <el-button type="text" class="notification-btn" @click="notificationPopoverVisible = !notificationPopoverVisible">
              <el-badge :value="notificationCount" :max="99">
                <el-icon><Bell /></el-icon>
              </el-badge>
            </el-button>
          </template>
          <div v-if="notifications.length">
            <div v-for="item in notifications" :key="item.id" class="notification-item" @click="handleNotificationClick(item)" style="padding:8px 0;cursor:pointer;">
              <div style="font-weight:bold;" :style="{color:!item.isRead?'#409EFF':'#333'}">{{ item.title }}</div>
              <div style="font-size:13px;color:#888;">{{ item.message }}</div>
              <div style="font-size:12px;color:#aaa;">{{ item.time }}</div>
              <el-tag size="small" :type="!item.isRead?'danger':'success'" style="margin-top:2px;">{{ !item.isRead?'未读':'已读' }}</el-tag>
            </div>
          </div>
          <div v-else style="text-align:center;color:#aaa;">暂无通知</div>
        </el-popover>
        <el-dropdown trigger="click">
          <div class="user-info">
            <el-avatar :size="32" :src="userStore.getPic || '/static/avatar.png'">
              <template #default>
                <span>{{ userInitial }}</span>
              </template>
            </el-avatar>
            <span class="username">{{ userStore.getUsername || '配送员' }}</span>
            <el-icon><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="$router.push('/delivery/profile')">
                <el-icon><User /></el-icon>
                个人信息
              </el-dropdown-item>
              <el-dropdown-item>
                <el-icon><Setting /></el-icon>
                系统设置
              </el-dropdown-item>
              <el-dropdown-item>
                <el-icon><Key /></el-icon>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <div class="main-container">
      <!-- 左侧菜单 -->
      <el-aside :width="isCollapse ? '64px' : '240px'" class="aside">
        <div class="menu-header">
          <el-button
            type="text"
            class="collapse-btn"
            @click="toggleCollapse"
          >
            <el-icon>
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-button>
          <span v-show="!isCollapse" class="menu-title">功能菜单</span>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="menu"
          :collapse="isCollapse"
          :collapse-transition="false"
          router
        >
          <!-- 首页 -->
          <el-menu-item index="/delivery/home">
            <el-icon><HomeFilled /></el-icon>
            <template #title>首页</template>
          </el-menu-item>

          <!-- 任务管理 -->
          <el-sub-menu index="tasks">
            <template #title>
              <el-icon><List /></el-icon>
              <span>任务管理</span>
            </template>
            <el-menu-item index="/delivery/tasks">
              <el-icon><Document /></el-icon>
              <span>我的任务</span>
            </el-menu-item>
            <el-menu-item index="/delivery/orders/pending">
              <el-icon><Clock /></el-icon>
              <span>待接单</span>
            </el-menu-item>
            <el-menu-item index="/delivery/orders/ongoing">
              <el-icon><Loading /></el-icon>
              <span>配送中</span>
            </el-menu-item>
            <el-menu-item index="/delivery/orders/completed">
              <el-icon><CircleCheck /></el-icon>
              <span>已完成</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 路线导航 -->
          <el-sub-menu index="routes">
            <template #title>
              <el-icon><Location /></el-icon>
              <span>路线导航</span>
            </template>
            <el-menu-item index="/delivery/routes/plan">
              <el-icon><MapLocation /></el-icon>
              <span>路线规划</span>
            </el-menu-item>
            <el-menu-item index="/delivery/routes/navigation">
              <el-icon><LocationFilled /></el-icon>
              <span>实时导航</span>
            </el-menu-item>
            <el-menu-item index="/delivery/routes/history">
              <el-icon><Histogram /></el-icon>
              <span>历史轨迹</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 货物管理 -->
          <el-sub-menu index="goods">
            <template #title>
              <el-icon><Box /></el-icon>
              <span>货物管理</span>
            </template>
            <el-menu-item index="/delivery/goods/collect">
              <el-icon><Collection /></el-icon>
              <span>货物收取</span>
            </el-menu-item>
            <el-menu-item index="/delivery/goods/exception">
              <el-icon><Warning /></el-icon>
              <span>异常处理</span>
            </el-menu-item>
          
          </el-sub-menu>

          <!-- 数据统计 -->
<!--          <el-menu-item index="/delivery/stats/weather">-->
<!--            <el-icon><Sunny /></el-icon>-->
<!--            <template #title>天气预报</template>-->
<!--          </el-menu-item>-->

          <!-- 消息中心 -->
          <el-menu-item index="/delivery/messages">
            <el-icon><Bell /></el-icon>
            <template #title>消息中心</template>
          </el-menu-item>

          <!-- 个人中心 -->
          <el-menu-item index="/delivery/profile">
            <el-icon><User /></el-icon>
            <template #title>个人中心</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主要内容区 -->
      <el-main class="main" :class="{ collapsed: isCollapse }">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/index.js'
import { getDeliveryNotifications, markNotificationAsRead } from '@/assets/delivery.js'
import {
  CaretBottom,
  User,
  Setting,
  SwitchButton,
  Expand,
  Fold,
  HomeFilled,
  List,
  Document,
  Clock,
  Loading,
  CircleCheck,
  Location,
  MapLocation,
  LocationFilled,
  Histogram,
  Box,
  Collection,
  Warning,
  Files,
  TrendCharts,
  Bell,
  Van,
  Sunny
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 菜单折叠状态
const isCollapse = ref(false)
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 当前时间
const currentTime = ref('')
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 通知相关
const notificationPopoverVisible = ref(false)
const notifications = ref([])
const notificationCount = computed(() => notifications.value.filter(n => !n.isRead).length)

const fetchNotifications = async () => {
  try {
    const response = await getDeliveryNotifications()
    if (response.status === 200 && response.data && response.data.data) {
      const sortedData = response.data.data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      notifications.value = sortedData.map(item => ({
        id: item.id,
        type: item.type,
        title: item.title,
        message: item.message,
        isRead: item.isRead,
        time: item.createdAt ? new Date(item.createdAt).toLocaleString('zh-CN') : ''
      }))
    } else {
      notifications.value = []
    }
  } catch (e) {
    notifications.value = []
  }
}

const handleNotificationClick = async (item) => {
  if (!item.isRead) {
    await markNotificationAsRead(item.id)
    item.isRead = true
  }
}

const userAvatar = computed(() => {
  if (userStore.getAvatar) return userStore.getAvatar
  const name = userStore.getUsername || '配送员'
  return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=10b981&color=fff`
})
const userInitial = computed(() => (userStore.getUsername ? userStore.getUsername[0] : '配'))

// 定时器
let timeInterval = null

onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  fetchNotifications()
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})

// 退出登录
const handleLogout = () => {
  // TODO: 实现退出登录逻辑
  router.push('/login')
}
</script>

<style scoped>
.delivery-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb;
}

/* 顶部导航栏样式 */
.header {
  height: 68px;
  background: linear-gradient(135deg,
  rgba(16, 185, 129, 0.98) 0%,
  rgba(5, 150, 105, 0.96) 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 28px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.12);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.12);
}

.header:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg,
  rgba(16, 185, 129, 0.2) 0%,
  rgba(5, 150, 105, 0.2) 100%);
  z-index: -1;
}

.header:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.16);
  background: linear-gradient(135deg,
  rgba(14, 165, 119, 0.98) 0%,
  rgba(4, 120, 87, 0.96) 100%);
  transform: translateY(-1px);
}

.logo {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 8px 16px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.08);
  transition: all 0.4s ease;
  position: relative;
  overflow: hidden;
}

.logo-icon {
  font-size: 24px;
  color: #fff;
}

.logo::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(
      to bottom right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.1) 50%,
      rgba(255, 255, 255, 0) 100%
  );
  transform: rotate(30deg);
  transition: all 0.6s ease;
}

.logo:hover {
  background: rgba(255, 255, 255, 0.12);
  transform: translateY(-2px);
}

.logo:hover::after {
  left: 100%;
  top: 100%;
}

.logo span {
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 0.5px;
  background: linear-gradient(90deg,
  #ffffff,
  rgba(224, 255, 244, 0.9));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1;
}

.header-center {
  display: flex;
  align-items: center;
}

.quick-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-1px);
}

.notification-btn {
  color: white;
  font-size: 18px;
  margin-right: 16px;
}

.user-info {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 18px;
  border-radius: 12px;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  background: rgba(255, 255, 255, 0.1);
  box-shadow:
      0 2px 8px rgba(0, 0, 0, 0.1),
      inset 0 1px 1px rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
}

.user-info::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
      to right,
      rgba(255, 255, 255, 0) 0%,
      rgba(255, 255, 255, 0.05) 50%,
      rgba(255, 255, 255, 0) 100%
  );
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow:
      0 4px 16px rgba(0, 0, 0, 0.12),
      inset 0 1px 1px rgba(255, 255, 255, 0.15);
}

.user-info:hover::before {
  transform: translateX(100%);
}

.username {
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 0.3px;
}

/* 左侧菜单样式 */
.main-container {
  display: flex;
  margin-top: 68px;
  min-height: calc(100vh - 68px);
}

.aside {
  background: #ffffff;
  border-right: 1px solid #e6e9f0;
  transition: width 0.3s ease;
  position: fixed;
  top: 68px;
  bottom: 0;
  left: 0;
  z-index: 999;
  box-shadow: 4px 0 20px rgba(0, 0, 0, 0.04);
}

.menu-header {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  border-bottom: 1px solid #e6e9f0;
  background: #fafbfc;
}

.menu-title {
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.collapse-btn {
  font-size: 20px;
  color: #606266;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  color: #10b981;
  transform: rotate(180deg);
}

/* 自定义菜单样式 */
:deep(.el-menu) {
  background: transparent;
  border-right: none;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s ease;
  position: relative;
  padding-left: 20px !important;
  margin: 2px 8px;
  border-radius: 8px;
}

:deep(.el-menu-item.is-active) {
  color: #ffffff;
  background: #10b981;
  border-right: none;
  border-left: 3px solid #10b981;
  transform: translateX(2px);
  font-weight: 500;
}

:deep(.el-menu-item:hover) {
  background: #ecfdf5;
  color: #10b981;
  transform: translateX(2px);
}

:deep(.el-menu-item .el-icon) {
  font-size: 18px;
  margin-right: 12px;
  min-width: 18px;
  transition: all 0.3s ease;
}

:deep(.el-menu-item:hover .el-icon),
:deep(.el-menu-item.is-active .el-icon) {
  color: #10b981;
  transform: scale(1.15);
}

:deep(.el-menu--collapse .el-menu-item .el-icon) {
  margin-right: 0;
}

/* 子菜单样式 */
:deep(.el-sub-menu) {
  margin: 2px 8px;
}

:deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s ease;
  border-radius: 8px;
  padding-left: 20px !important;
}

:deep(.el-sub-menu__title:hover) {
  background: #ecfdf5;
  color: #10b981;
}

:deep(.el-sub-menu__title .el-icon) {
  font-size: 18px;
  margin-right: 12px;
  min-width: 18px;
  transition: all 0.3s ease;
}

:deep(.el-sub-menu__title:hover .el-icon) {
  color: #10b981;
  transform: scale(1.15);
}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: #10b981;
  background: #ecfdf5;
}

/* 主要内容区 */
.main {
  flex: 1;
  margin-left: 240px;
  padding: 0;
  transition: margin-left 0.3s ease;
  background-color: transparent;
}

.main.collapsed {
  margin-left: 64px;
}

/* 下拉菜单高级样式 */
:deep(.el-dropdown-menu) {
  border-radius: 14px;
  box-shadow:
      0 12px 32px rgba(0, 0, 0, 0.16),
      0 2px 6px rgba(0, 0, 0, 0.08);
  border: none;
  transform-origin: top right;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  padding: 8px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  font-size: 15px;
  transition: all 0.3s ease;
  color: #606266;
  border-radius: 8px;
  margin: 4px 0;
  position: relative;
  overflow: hidden;
}

:deep(.el-dropdown-menu__item::before) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background: #10b981;
  transform: translateX(-10px);
  transition: transform 0.3s ease;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(16, 185, 129, 0.08);
  transform: translateX(4px);
  color: #10b981;
}

:deep(.el-dropdown-menu__item:hover::before) {
  transform: translateX(0);
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 0;
  color: #909399;
  font-size: 16px;
  transition: all 0.3s ease;
}

:deep(.el-dropdown-menu__item:hover .el-icon) {
  color: #10b981;
  transform: scale(1.1);
}

:deep(.el-dropdown-menu__item.divided) {
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

:deep(.el-dropdown-menu__item.divided::before) {
  content: '';
  position: absolute;
  top: -1px;
  left: 20px;
  right: 20px;
  height: 1px;
  background: rgba(255, 255, 255, 0.1);
}

/* 路由切换动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .header {
    padding: 0 20px;
  }
  
  .quick-stats {
    gap: 15px;
  }
  
  .stat-item {
    font-size: 13px;
    padding: 4px 10px;
  }
}

@media (max-width: 768px) {
  .header-center {
    display: none;
  }
  
  .logo span {
    font-size: 18px;
  }
  
  .aside {
    width: 64px !important;
  }
  
  .main {
    margin-left: 64px;
  }
}
</style> 